package stancel.peter.smslogger.activities;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import stancel.peter.smslogger.Contact;
import stancel.peter.smslogger.ContactsAdapter;
import stancel.peter.smslogger.R;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;

/**
 * Sluzi na vyberanie kontaktov a na vytvorenie suboru "SmsFilter.txt"
 * s telefonnymi cislami sluziaceho ako filter.
 * @author Peter Stancel
 */
public class ContactsActivity extends Activity{
	
	private List<Contact> list;
	private ContactsAdapter contactAdapter;
	
	/**
	 * Vola sa pri vytvarani aktivity. Nastavuje adapter.
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		
		setContentView(R.layout.contacts);
		
        list = new ArrayList<Contact>();
        
        contactAdapter = new ContactsAdapter(this, list);
        ListView listView = (ListView) findViewById(R.id.contacts_listView);
		listView.setAdapter(contactAdapter);
	}
	
	/**
	 * Ziska vsetky telefonne cisla z kontaktov telefonu
	 * a ulozi ich do listu.
	 */
	@Override
	protected void onStart() {
		super.onStart();
		
		// zabezpeci, aby sa telefonne cisla neopakovali
		String WHERE_CONDITION = "1=1) GROUP BY (" + Phone.NUMBER;
	    String[] PROJECTION = {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER};
	    String SORT_ORDER = Phone.DISPLAY_NAME;

		Cursor cursor = getContentResolver().query( Phone.CONTENT_URI, PROJECTION, WHERE_CONDITION, null, SORT_ORDER); 
        startManagingCursor(cursor);
        
        String numbers = loadFromFile();
        
        while (cursor.moveToNext()) {
			String name = cursor.getString(1);
			String number = cursor.getString(2);
			
			list.add(new Contact(name, number, numbers.contains(number)));
		}
	}
	
	/**
	 * Vola sa pri stlaceni tlacidla Menu na zariadeni.
	 * Vytvara Hlavne menu.
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_option_contacts_activity, menu);
		return true;
	}
	
	/**
	 * Podla vybraneho itemu v OptionsMenu nastavi <i>checked</i>.
	 * <i>select_all</i> - <i>checked</i> = true
	 * <i>deselect_all</i> - <i>checked</i> = false
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		switch (item.getItemId()) {
			case (R.id.select_all): {
				selectAll(true);
				return true;
			}
			case (R.id.deselect_all): {
				selectAll(false);
				return true;
			}
		}
		return false;
	}
	
	/**
	 * Nastavi <i>checked</i> podla vstupneho parametru.
	 * @param checked
	 */
	private void selectAll(boolean checked){
		for (Contact contact : list) {
			contact.setChecked(checked);
		}
		contactAdapter.notifyDataSetChanged();
	}
	
	/**
	 * Vola sa ak sa aktivita dostane z popredia do pozadia.
	 * Vola metodu na ulozenie telefonnych cisel, ktore maju
	 * <i>checked</i> na true do suboru "SmsFilter.txt".
	 */
	@Override
	protected void onPause() {
		super.onPause();
		saveToFile();
	}
	

	/**
	 * Vola sa pred tym, ako je aktivita znicena.
	 * Vola metodu na ulozenie telefonnych cisel, ktore maju
	 * <i>checked</i> na true do suboru "SmsFilter.txt".
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		saveToFile();
	}
	
	/**
	 * Vola sa, ak sa aktivita vratila spat do popredia.
	 */
	@Override
	protected void onResume() {
		super.onResume();
		contactAdapter.notifyDataSetChanged();
	}
	
	/**
	 * Nacita subor "SmsFilter.txt" s telefonnymi cislami,
	 * ktore ulozi do <i>numbers</i>.
	 * @return numbers String s telefonnymi cislami.
	 */
	private String loadFromFile() {
		StringBuilder numbers = new StringBuilder();
		try {
			File file = new File(Environment.getExternalStorageDirectory(), "SmsLogger");
			File fileOutput = new File(file, "SmsFilter.txt");
			file.mkdir();

			BufferedReader buf = new BufferedReader(new FileReader(fileOutput));
			String line;
			while((line = buf.readLine()) != null){
				numbers.append(line +"\n");
			}
		    buf.close();
		} catch (FileNotFoundException e) {
			// Subor neexistuje.
			// Moze to nastat ak sa spusti aplikacia prvykrat.
		} catch (IOException e) {
			Toast.makeText(this, R.string.error_external_storage, Toast.LENGTH_SHORT).show();
		}
		return numbers.toString();
	}
	
	/**
	 * Ulozi vsetky telefonne cisla v liste, ktore maju
	 * nastavene <i>checked</i> na true.
	 */
	private void saveToFile() {
		try {
			File file = new File(Environment.getExternalStorageDirectory(), "SmsLogger");
			File fileOutput = new File(file, "SmsFilter.txt");
			file.mkdir();
			
			BufferedWriter buf = new BufferedWriter(new FileWriter(fileOutput, false));
			for (Contact contact : list) {
				if(contact.isChecked()){
					buf.write(contact.getNumber()+"\n");
				}
			}
		    buf.flush();
		    buf.close();
		} catch (FileNotFoundException e) {
			// Subor neexistuje.
			// Moze to nastat ak sa spusti aplikacia prvykrat.
		} catch (IOException e) {
			Toast.makeText(this, R.string.error_external_storage, Toast.LENGTH_SHORT).show();
		}
	}
}